package xiaye.crawler.core.impl;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

import xiaye.crawler.core.Frontier;
import xiaye.crawler.domain.Page;
import xiaye.crawler.exception.FrontierEmptyException;

public class SimpleFrontier implements Frontier{
	private int count = 0;
	private BlockingQueue<URI> queue;
	
	public SimpleFrontier(){
		init();
	}
	
	private void init(){
		queue = new LinkedBlockingQueue<URI>();
		try {
			queue.add(new URI("http://www.google.com/").normalize());
			queue.add(new URI("http://www.blogbus.com/").normalize());
		} catch (URISyntaxException e) {
			e.printStackTrace();
		}
	}
	
	public URI getNext() throws FrontierEmptyException{
		try {
			URI next = queue.poll(30, TimeUnit.SECONDS);
			if (next == null){
				throw new FrontierEmptyException();
			}
			return next;
		} catch (InterruptedException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public void processPage(Page page) {
		for (URI uri : page.getOutlinks()){
			queue.add(uri);
			System.out.println(uri);
		}
	}
}
